<?php

namespace App\Http\Controllers;

use App\Cate;
use App\Code;
use App\Collect;
use App\Msg;
use App\Question;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class QuestionController extends Controller
{
    //
    public function index()
    {
        $where = \request()->all();
        unset($where['page']);
        foreach ($where as $k=>$value){
            if ($value==""){
                unset($where[$k]);
            }
        }
        $hotQuestions = Question::where('created_at','>',Carbon::now()->modify('-7 days'))->take(10)->withCount('answers')->orderBy('answers_count','desc')->get();
        $questions = Question::orderBy('created_at','desc')->where($where)->paginate(5);
        return view("question.index",compact('questions','hotQuestions','where'));
    }
    public function create(Code $code)
    {
        $cates = Cate::all();
        $code = $code->getRand();
        return view("question.create",compact('cates','code'));
    }
    public function store(Request $request)
    {
        if(session('answer') != $request->vercode)
        {
            return ['error'=>1,'info'=>'验证码错误'];
        };
        $this->validate($request,[
            'title'=>'max:20|min:3',
            'content'=> 'min:3',
            'kiss'=>'in:[10,20,30,40,50,60,70,80,90,100]',
        ]);
        $ques = request(['cate_id','title','content','kiss']);
        $ques['user_id'] = \Auth::id();
        if (empty($request->desc['content'])||$request->cate_id ==1){
            $ques['desc'] = json_encode($request->desc);
        }
        $question = Question::create($ques);
        return [
            'error'=>0,
            'info'=>'发布成功',
            'url'=>'/question/'.$question->id.'/show',
        ];
    }
    public function show(Question $question)
    {
        $hotQuestions = Question::where('created_at','>',Carbon::now()->modify('-7 days'))->take(10)->withCount('answers')->orderBy('answers_count','desc')->get();
        $question->view_num++;
        $question->save();
        $answers = $question->answers()->orderBy('status','desc')->orderBy('created_at','desc')->paginate(5);
        return view("question.show",compact('question','hotQuestions','answers'));
    }
    public function upload(Request $request)
    {
        if ($request->isMethod('post')) {

            $file = $request->file('file');
            // 文件是否上传成功
            if ($file->isValid()) {
                // 获取文件相关信息
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                // 上传文件
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                if ($bool){
                    return[
                        "code"=>0 //0表示成功，其它失败
                        ,"data"=>[
                            "src"=>"/uploads/".$filename
                        ]

                    ];
                }
            }
        }
    }

    public function collection(Question $question)
    {
        $res = $question->oneCollect(\Auth::id());
        $collect = new Collect();
        $data = ['user_id'=>\Auth::id(),'question_id'=>$question->id];
        $info =[
            'question_id' => $question->id,
            'source_id' => \Auth::id(),
            'target_id' => $question->user->id,
            'operate' => '收藏',
        ];
        if(!$res->exists()){
            $collect->create($data);
            Msg::create($info);
            return [
              'error'=>0,
              'info'=>'收藏成功'
            ];
        }else{
            $collect->where($data)->delete();
            Msg::where($info)->delete();
            return [
                'error'=>0,
                'info'=>'取消收藏'
            ];
        }
    }
}
